package com.imooc.ad.index.adplan;


import com.imooc.ad.index.IndexAwre;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class AdPlanIndex implements IndexAwre<Long, AdPlanObject> {

    //定义一个map,用来存储索引
    private static Map<Long, AdPlanObject> indexMap;
    //初始化Map，使用线程安全的ConcurrentHashMap
    static {
        indexMap = new ConcurrentHashMap<>();
    }

    @Override
    public AdPlanObject get(Long key) {
        return indexMap.get(key);
    }

    @Override
    public void add(Long key, AdPlanObject value) {
        log.info("before add: {}", indexMap);
        indexMap.put(key,value);
        log.info("after add: {}", indexMap);

    }

    @Override
    public void update(Long key, AdPlanObject value) {
        log.info("before update: {}", indexMap);

        AdPlanObject oldIndex = indexMap.get(key);
        if (null != oldIndex){
            indexMap.put(key, value);
        } else {
            oldIndex.update(value);
        }
        log.info("after update: {}", indexMap);
    }

    @Override
    public void delete(Long key, AdPlanObject value) {

        log.info("before delete: {}", indexMap);
        indexMap.remove(key);
        log.info("after delete: {}", indexMap);

    }
}
